package com.freedom.org.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.baomidou.mybatisplus.toolkit.CollectionUtils;
import com.freedom.auth.vo.EmployeeExportVo;
import com.freedom.auth.vo.EmployeeImportVo;
import com.freedom.auth.vo.ErrorExportVo;
import com.freedom.base.context.LoginContext;
import com.freedom.base.query.BaseQuery;
import com.freedom.base.util.AjaxResult;
import com.freedom.base.util.PageInfo;
import com.freedom.clue.verifyHandler.EmployeeVerifyHandler;
import com.freedom.org.domain.Department;
import com.freedom.org.domain.Employee;
import com.freedom.org.mapper.DepartmentMapper;
import com.freedom.org.mapper.EmployeeMapper;
import com.freedom.org.query.EmployeeQuery;
import com.freedom.org.service.IEmployeeService;
import com.freedom.base.service.impl.BaseServiceImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.assertj.core.internal.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author freedom
 * @since 2023-10-13
 */
@Service
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {

    @Autowired
    private EmployeeMapper mapper;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private EmployeeVerifyHandler employeeVerifyHandler;

    @Override
    public Employee getByName ( Employee employee ) {
        return mapper.getByName(employee);
    }

    @Override
    public Employee getByUserName ( String username ) {
        return mapper.getByUserName(username);
    }



    @Override
    public String importExcel ( MultipartFile file ) throws Exception {
        ImportParams importParams = new ImportParams();
        //表格标题行数,默认0
        importParams.setTitleRows(0);
        //是否需要校验上传的Excel
        importParams.setNeedVerify(true);
        //告诉easypoi我们自定义的验证器
        importParams.setVerifyHandler(employeeVerifyHandler);
        InputStream fileInputStream = file.getInputStream();
        ExcelImportResult<EmployeeImportVo> result = ExcelImportUtil.importExcelMore(fileInputStream, EmployeeImportVo.class, importParams);
        if (!result.isVerifyFail() && !CollectionUtils.isEmpty(result.getList())) {
            for (EmployeeImportVo vo : result.getList()) {
                String departmentName = vo.getDepartmentName();
                Department departmentMapperByName = departmentMapper.getByName(departmentName);
                if(departmentMapper.getAll().contains(departmentMapperByName)){
                    importExcelInsert(vo);
                }else{
                    departmentMapper.insert(new Department(vo.getDepartmentName()));
                    importExcelInsert(vo);
                }
            }
        } else {
            List<ErrorExportVo> errorExportVoList = new ArrayList<>();
            // 错误数据
            for (EmployeeImportVo vo : result.getFailList()) {
                ErrorExportVo errorExportVo = new ErrorExportVo();
                if (!Objects.isNull(vo.getErrorMsg())) {
                    // 获取所有错误数据导出为excel表
                    errorExportVo.setId(null);
                    errorExportVo.setUsername(vo.getUsername());
                    errorExportVo.setPassword(vo.getPassword());
                    errorExportVo.setEmail(vo.getEmail());
                    errorExportVo.setHeadImage(vo.getHeadImage());
                    errorExportVo.setPhone(vo.getPhone());
                    errorExportVo.setDepartmentName(vo.getDepartmentName());
                    errorExportVo.setErrorMsg(vo.getErrorMsg());

                    errorExportVoList.add(errorExportVo);
                }else{
                    // 正确数据
                    departmentMapper.insert(new Department(vo.getDepartmentName()));
                    importExcelInsert(vo);
                }
            }

            ExportParams params = new ExportParams("导出错误数据表", "sheet", ExcelType.XSSF);

            Workbook workbook = ExcelExportUtil.exportExcel(params, ErrorExportVo.class, errorExportVoList);


            FileOutputStream fos = new FileOutputStream("C:\\Users\\freedom\\Desktop\\test\\error.xlsx");

            workbook.write(fos);

            fos.close();

//            System.out.println(("校验失败的详细为 ：{}" + vo));
            return "文档校验失败";
        }
        return "导入成功";
    }

    private void importExcelInsert ( EmployeeImportVo vo ) {
        Department department = departmentMapper.getByName(vo.getDepartmentName());
        Employee employee = new Employee();
        employee.setDepartment(department);
        BeanUtils.copyProperties(vo, employee);
        this.insert(employee);
    }


    @Override
    public List<EmployeeExportVo> getClueExportList () {
        Object query = LoginContext.queryMap.get("query");
        List<Employee> list = mapper.queryPage((BaseQuery) query);

//        List<Employee> list = mapper.getAll();


        return list.stream().map(employee -> {
            EmployeeExportVo vo = new EmployeeExportVo();

            String name = employee.getDepartment().getName();
            vo.setDepartmentName(name);

            BeanUtils.copyProperties(employee, vo);
            return vo;
        }).collect(Collectors.toList());
    }

}
